import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactEcharts from 'echarts-for-react';

class EchartsLine extends Component {

  static defaultProps = {
    title: '',
    fontColor: 'black',
  }

  constructor(props) {
    super(props);
    const {title, fontColor, legends, datas} = this.props;
    this.option = this.buildOption(title, fontColor, legends, datas);
  }

  buildOption = (title, fontColor, legends, datas) => {
    const series = datas.map((data, index)=>({
        name: legends[index],
        type: 'line',
        smooth: true,
        // areaStyle: {normal: {}},
        data: data
    }));
    return ({
      title: {
        text: title,
        left: 'center',
        textStyle: {
          color: fontColor
        }
      },
      tooltip: {
        trigger: 'axis',
          axisPointer: {
          type: 'cross',
            label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      legend: {
        left: 'left',
        textStyle: {
          color: fontColor
        },
        data: [...legends]
      },
      grid: {
        left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        axisLine: {
          lineStyle: {
            color: fontColor
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: fontColor
          }
        }
      },
      series
    })
  };

  updateChart = (legends, datas) => {
    this.option.legend.data = legends;
    this.option.series = datas.map((data, index)=>({
      name: legends[index],
      type: 'line',
      smooth: true,
      areaStyle: {normal: {}},
      data: data
    }));
    if(this.echarts) {
      this.echarts.getEchartsInstance().setOption(this.option);
    }
  }

  render() {
    return (
      <ReactEcharts
        ref={(e) => { this.echarts = e; }}
        notMerge={true}
        lazyUpdate={true}
        option={this.option}
        style={this.props.fontColor==='white'?{width: '100%',height:'100%'}:''}
      />
    );
  }
}

EchartsLine.proTypes = {
  title: PropTypes.string,
  legends: PropTypes.array.isRequired,
  datas: PropTypes.array.isRequired
}

export default EchartsLine;
